package com.beigai.imessage.client;

import com.beigai.imessage.client.dto.IPAddress;
import com.beigai.imessage.client.dto.IRequest;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created by xxl on 2017/5/10.
 */
public class SocketClient implements IClient {
    private Selector selector;
    private SocketChannel channel;

    public void initClient(IPAddress ipAddress) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(ipAddress.getHost(), ipAddress.getPort()));
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    public void listen() throws IOException {
        while (true) {
            selector.select();
            Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = ite.next();
                ite.remove();
                if (key.isConnectable()) {
                    channel = (SocketChannel) key.channel();
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false);
                    channel.register(this.selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    String msg = read(key);
                }
            }
        }
    }

    /**
     * 处理读取服务端发来的信息 的事件
     *
     * @param key
     * @throws IOException
     */
    public String read(SelectionKey key) throws IOException {
        // 服务器可读取消息:得到事件发生的Socket通道
        SocketChannel channel = (SocketChannel) key.channel();
        // 创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(10);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data, "UTF-8").trim();
        return msg;
    }

    //根据连接channel发送消息给服务器
    public void write(IRequest iRequest) throws IOException {
        channel.write(ByteBuffer.wrap(iRequest.getMessage()));
    }


}
